<template>
  <div class="user-nav">
    <router-link class="home-link" to="/">回到首页</router-link>
    <div class="flex-grow"></div>
    <div v-if="isEmpty(loginUser)">
      <router-link to="/login">登录</router-link>
      <router-link to="/register">注册</router-link>
    </div>
    <div v-if="!isEmpty(loginUser)">
      <a-upload
          v-model:file-list="fileList"
          name="avatar"
          :headers="{token: loginUser.token}"
          :show-upload-list="false"
          :action="$baseURL+'/user/avatar'"
          @change="handleChange"
          method="post"
      >
        <a-avatar
            size="large"
            shape="square"
            style="background-color: #f56a00"
            :src="'data:image/jpeg;base64,'+loginUser.base64Data">
          <template #icon><UserOutlined /></template>
        </a-avatar>
      </a-upload>
      <router-link to="/home">
        <span>欢迎，{{loginUser.nickname}}</span>
      </router-link>
      <router-link to="/home?tab=4">
        <a-badge :count="notificationCount" />
      </router-link>

      <a href="javascript:void(0)" @click="logout">退出</a>
<!--      <a-button type="primary" @click="openNotification({content:'test123'})">测试通知</a-button>-->

    </div>
  </div>
</template>

<script>
import utils from '@/utils/utils.js';
import { UserOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { notification, Button } from 'ant-design-vue';
import { h } from 'vue';
import axios from "axios";
export default {
  name: "Header.vue",
  components: {
    UserOutlined,
  },
  data(){
    return{
      fileList:[],
      notificationCount:0
    }
  },
  methods:{
    logout(){
      this.$store.commit('setUser', {})
    },
    isEmpty(obj){
      return utils.isEmpty(obj);
    },
    handleChange(info){
      if (info.file.status !== 'uploading') {
        console.log('uploading')
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        // console.log('done',info.file.response)
        message.success(`${info.file.name} file uploaded successfully`);
        this.$store.commit('setUserAvatar',info.file.response.data)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    close(){
      console.log('Notification was closed. Either the close button was clicked or duration time elapsed.');
    },
    openNotification(notice){
      this.notificationCount++
      const key = `open${Date.now()}`;
      notification.open({
        message: '通知',
        description: notice.content,
        btn: () => h(Button, {
          type: 'primary',
          size: 'small',
          onClick: () => {
            notification.close(key)
            console.log("已读")
            this.changeReadStatus(notice.id)
            this.notificationCount--
          }

        }, {
          default: () => '已阅',
        }),
        key,
        onClose: this.close,
      });
    },
    openws(){
      let ws = new WebSocket('ws://localhost:8088/notice/' + this.loginUser.id);
      ws.onopen = function() {
        console.log("Connected to the chat server");
        // ws.send("Hello, server!");
      };

      ws.onmessage = event => {
        console.log("Received from chat server: " , event.data);
        let notice = JSON.parse(event.data)
        console.log(notice)
        this.openNotification(notice)
      };

      ws.onclose = function() {
        console.log("Disconnected from the server");
      };

      ws.onerror = function(event) {
        console.log("Error: " + event.data);
      };
    },
    changeReadStatus(id){
      axios.put("/notice/update/status",{
        id:id,
        readStatus:'Read'
      }).then(res => {
        console.log("更新成功")
      })
    }
  },
  created(){
    if(this.loginUser.id){
      this.openws()
    }

  },
  mounted(){

  },
  // 在组件中定义计算属性
  computed: {
    loginUser() {
      return this.$store.state.user;
    }
  }
}
</script>

<style scoped>
.user-nav {
  display: flex;
  align-items: center;
  padding: 1em;
  background-color: #f3f3f3;
}
.user-nav span, .user-nav a {
  margin-right: 1em;
  color: #007BFF;
  text-decoration: none;
}
.user-nav a:last-child {
  margin-right: 0;
}
.user-nav .flex-grow {
  flex-grow: 1;
}
.user-nav .home-link {
  margin-right: auto;
}
</style>